import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

// 支持无界主应用传递基础路由前缀：window.routerBase 或 window.__WUJIE?.routerBase
function normalizeBase(base?: string): string {
  if (!base) return import.meta.env.BASE_URL
  let b = base.trim()
  if (!b.startsWith('/')) b = '/' + b
  // History 模式需要末尾斜杠，确保路由前缀规范
  if (!b.endsWith('/')) b = b + '/'
  return b
}

const w = (typeof window !== 'undefined' ? (window as any) : {})
const injectedBase: string | undefined = (w.__WUJIE?.props?.routerBase) || w.__WUJIE?.routerBase || w.routerBase
const base = normalizeBase(injectedBase)

// Hash 基础前缀：去掉末尾斜杠，避免形成 #/base//route
function makeHashBase(b: string): string {
  return b.endsWith('/') ? b.slice(0, -1) : b
}

// 无界（Wujie）与 Electron（file://）使用 Hash，其它使用 History
const isFileProtocol = typeof window !== 'undefined' && window.location.protocol === 'file:'
const isHostedByWujie = !!(w.__POWERED_BY_WUJIE__ || w.__WUJIE)
const useHash = isFileProtocol || isHostedByWujie
const history = useHash
  ? createWebHashHistory(makeHashBase(base))
  : createWebHistory(base)

const router = createRouter({
  history,
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
})

export default router
